<template>
  <div>
    <!-- 面包屑导航开始 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航结束 -->
    <!-- 卡片区域开始 -->
    <el-card class="box-card">
      <!-- 搜索框和添加用户按钮开始 -->
      <el-row :gutter="20">
        <el-col span="8">
          <el-input clearable placeholder="请输入内容" v-model="queryInfo.query" @clear="getTableList">
            <el-button @click="getTableList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col span="3">
          <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 搜索框和添加用户按钮结束 -->
      <!-- 用户表格区域开始 -->
      <el-table :data="TableList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="handleUserStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip :enterable="false" effect="dark" content="编辑" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="handleEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" effect="dark" content="分配权限" placement="top">
              <el-button
                @click="handleGiveRoles(scope.row)"
                type="warning"
                icon="el-icon-share"
                size="small"
              ></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" effect="dark" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="handleRemoteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户表格区域结束 -->
      <!-- 分页区域开始 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 分页区域结束 -->
    </el-card>
    <!-- 卡片区域结束 -->
    <!-- 添加用户的对话框开始 -->
    <el-dialog title="添加用户" :visible.sync="addUserdialogVisible" @close="handleAddDialogClose">
      <!-- 添加用户表单开始 -->
      <el-form
        ref="newUserFormRef"
        :model="newUserFormData"
        :rules="newUserFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUserFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUserFormData.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUserFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="newUserFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加用户表单结束 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddUserRequest">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户的对话框结束 -->
    <!-- 编辑用户的对话框开始 -->
    <el-dialog title="编辑用户" :visible.sync="editUserdialogVisible" @close="handleEditDialogClose">
      <!-- 编辑用户表单开始 -->
      <el-form
        ref="editUserFormRef"
        :model="editUserFormData"
        :rules="editUserFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserFormData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 编辑用户表单结束 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditUserRequest">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户的对话框结束 -->
    <!-- 分配权限的对话框开始 -->
    <el-dialog
      @close="handleGiveRolesDialogClose"
      title="分配权限"
      :visible.sync="GiveRolesdialogVisible"
    >
      <div>当前的用户: {{UserInfo.username}}</div>

      <div>当前的角色: {{UserInfo.role_name}}</div>
      <div>
        分配新角色:
        <!-- 包含所有角色的下拉选择框 -->
        <el-select v-model="SelectId" placeholder="请选择">
          <el-option
            v-for="item in SelectData"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
        <!-- 包含所有角色的下拉选择框 -->
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="GiveRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleGiveRolesRequest">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框结束 -->
  </div>
</template>

<script>
export default {
  data() {
    // 校验邮箱是否合法的自定义校验规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
      if (!regEmail.test(value)) {
        return callback(new Error("邮箱不合法"));
      }
      callback();
    };
    // 校验手机号是否合法的自定义校验规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if (!regMobile.test(value)) {
        return callback(new Error("手机号不合法"));
      }
      callback();
    };
    return {
      // 获取用户列表的请求数据
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 8
      },
      // 返回的用户列表数据
      TableList: [],
      // 用户总数(分页组件的总条数)
      total: "",
      // 分配权限对话框用的数据
      UserInfo: {},
      // 下拉框用的数据
      SelectData: [],
      // 下拉框选择之后的ID
      SelectId: "",
      // 控制添加用户对话框的显示与隐藏
      addUserdialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      editUserdialogVisible: false,
      // 控制分配权限对话框的显示与隐藏
      GiveRolesdialogVisible: false,
      // 添加用户对话框里的表单绑定的数据
      newUserFormData: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加用户对话框里的表单验证规则
      newUserFormRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "电话不能为空", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 编辑用户对话框里的表单数据
      editUserFormData: {},
      // 编辑用户对话框里的表单数据验证规则
      editUserFormRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "电话不能为空", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getTableList();
  },
  methods: {
    // 获取用户列表
    async getTableList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.TableList = res.data.users;
      this.total = res.data.total;
    },
    // 当每页多少条数据改变时(1，5，8)
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize;
      this.getTableList();
    },
    // 当页码改变时
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum;
      this.getTableList();
    },
    // 用户状态switch切换时
    async handleUserStateChange(uesrinfo) {
      const { data: res } = await this.$http.put(
        `users/${uesrinfo.id}/state/${uesrinfo.mg_state}`
      );
      console.log(res);

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success("修改成功");
    },
    // 点击添加用户按钮
    handleAddUser() {
      this.addUserdialogVisible = true;
    },
    // 添加用户对话框关闭
    handleAddDialogClose() {
      this.$refs.newUserFormRef.resetFields();
    },
    // 添加用户对话框表单提交请求
    handleAddUserRequest() {
      this.$refs.newUserFormRef.validate(async value => {
        if (!value) return;
        const { data: res } = await this.$http.post(
          "users",
          this.newUserFormData
        );
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.addUserdialogVisible = false;
        this.getTableList();
      });
    },
    // 编辑用户对话框关闭
    handleEditDialogClose() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 获取当前点击的那个用户信息
    async handleEditDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) return this.$message.error("编辑失败");
      this.editUserFormData = res.data;
      this.editUserdialogVisible = true;
    },
    // 编辑用户对话框表单提交请求
    handleEditUserRequest() {
      this.$refs.editUserFormRef.validate(async value => {
        if (!value) return;
        const { data: res } = await this.$http.put(
          `users/${this.editUserFormData.id}`,
          {
            id: this.editUserFormData.id,
            email: this.editUserFormData.email,
            mobile: this.editUserFormData.mobile
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.editUserdialogVisible = false;
        this.$message.success("编辑成功");
        this.getTableList();
      });
    },
    // 删除用户请求
    async handleRemoteUser(id) {
      try {
        const confirm = await this.$confirm("确认删除该用户吗?", "提示", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        });
        if (confirm == "confirm") {
          const { data: res } = await this.$http.delete(`users/${id}`);
          console.log(res);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          this.getTableList();
        }
      } catch (error) {
        this.$message.info("已取消删除");
      }
    },
    // 点击分配权限按钮
    async handleGiveRoles(role) {
      this.UserInfo = role;
      const { data: res } = await this.$http.get("roles");
      this.SelectData = res.data;
      this.GiveRolesdialogVisible = true;
    },
    // 分配权限对话框提交请求
    async handleGiveRolesRequest() {
      const { data: res } = await this.$http.put(
        `users/${this.UserInfo.id}/role`,
        {
          rid: this.SelectId
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getTableList();
      this.GiveRolesdialogVisible = false;
    },
    // 分配权限对话框关闭
    handleGiveRolesDialogClose() {
      this.SelectId = "";
      this.UserInfo = {};
    }
  }
};
</script>

<style lang="less" scoped>
</style>>

